﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Lm.Common.ExtensionMethods
{
    public static class ListExt
    {
        public static List<List<T>> Paging<T>(this List<T> list, int pageSize)
        {
            var result = new List<List<T>>();
            var totalPage = Math.Ceiling(((decimal)list.Count) / ((decimal)pageSize));
            for (int i = 1; i <= totalPage; i++)
            {
                result.Add(
                    list.Skip((i - 1) * pageSize).Take(pageSize).ToList()
                    );
            }
            return result;
        }
        public static DataTable ToDateTable<T>(this List<T> list) where T : IModel
        {
            var dt = new DataTable();
            foreach (var p in typeof(T).GetProperties())
            {
                if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                { dt.Columns.Add(p.Name, p.PropertyType.GetGenericArguments().First()); }
                else
                { dt.Columns.Add(p.Name, p.PropertyType); }
            }
            foreach (var i in list)
            {
                var row = dt.NewRow();
                i.ToRow(row, SchemaNotSame.ThrowException);
                dt.Rows.Add(row);
            }
            return dt;
        }
    }
}
